$(function () {
	/******************************************初始化部分******************************************/
	const table=layui.table;
	// 选中的数据资源的id数组
	let sourceIdList=[]
	// 数据资源查询参数
	let dataSourceParame={
		createUserId: sessionStorage.getItem("UserId"),
		currPage:0,
		pageSize:10,
		keyword:""
	}
	// 数据资源表格实例
	const dataSourceTable= table.render({
		id:'dataSourceTable',
		elem: '#dataSourceTable'
		,height: '.layui-tab-item'
		,data:[]
		// ,page: true //开启分页
		,cols: [[ //表头
			{type:'checkbox', width:60},
			{type:'numbers', title: '序号', width:60}
			,{field: 'contentName', title: '资源名称', width:200}
			// ,{field: 'controlRuleName', title: '可见规则'}
			,{field: 'sourceName', title: '所属数据通道'}
			,{field: 'keyWords', title: '关键字'
				,
				templet:function (d)
				{
					if (d.keyWords==='[]'){
						return `<span>暂无</span> `
					}else {
						return `<span>${d.keyWords}</span> `
					}
				}}
			,{field: 'status', title: '当前状态', width:90,templet:
					function (d){
						const status=d.status;
						switch (status) {
							case -2:
								return `<span>审核失败</span>`
							case -1:
								return `<span>保存</span>`
							case 0:
								return `<span>正常</span>`
							case 1:
								return `<span>故障</span>`
							case 2:
								return `<span>未审核</span>`
							case 3:
								return `<span>未测试</span>`
						}
					}
			}
			// ,{field: 'remark', title: '备注', width: 160,}
			,{  title: '操作', width: 180, templet:function (d){
					switch (d.status){
						case -2:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
						case -1:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
						case 0:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
						case 1:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
						case 2:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
						case 3:
							return `
						<a class="layui-btn layui-btn-danger layui-btn-xs text-white" lay-event="delete">删除</a>
						<a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">编辑</a>
						`
					}
				}
			},

		]]
	})
	/******************************************事件处理部分******************************************/
	//数据资源注册
	$("#dataRegistrat").click(function () {
		// window.dataProductId = null;
		// layer.open({
		// 	type: 2,
		// 	title: "数据注册",
		// 	area: ['600px', '380px'],
		// 	content: ['./popupPage/registerDataSourcePop.html', 'no']
		// });
		window.location.href = "./dataSourceRegister.html";
	})

	// 数据资源批量审核复选框
	table.on('checkbox(dataSourceTableFilter)', function(obj){
		console.log('obj', obj)
		if (obj.type==='all'&&obj.checked){//选中
			 sourceIdList=table.cache['dataSourceTable'].map(item=>item.id);
			console.log('sourceIdList', sourceIdList)
		}else if (obj.type==='one'&&obj.checked){//选中
			sourceIdList.push(obj.data.id)
			console.log('sourceIdList', sourceIdList)
		}else if (obj.type==='all'&&!obj.checked){//取消选中
			sourceIdList=[]
		}else if (obj.type==='one'&&!obj.checked){//取消选中
			// 查找值的索引
			const index = sourceIdList.indexOf(obj.data.id);
			if (index !== -1) {
				sourceIdList.splice(index, 1);
			}
		}
	});
	// 数据资源表格操作
	layui.table.on('tool(dataSourceTableFilter)', function(obj){
		const data = obj.data;
		console.log('data', data)
		if(obj.event === 'edit') {
			window.location.href=`./dataSourceRegister.html?id=${data.id}`
		}else if (obj.event==='delete'){
			$.ajax({
       timeout:30000,
				url: window.Http + `/datasourceContent/del/${data.id}`,
				type: 'DELETE',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code===200){
						layer.msg('删除成功');
						dataSourceListReq(dataSourceParame).then(res=>{
							dataSourceTable.reload({data:res.rows})
						})
					}else {
						layer.msg(res.msg)
					}
				}
			})
		}
	})
	// 批量提交审核数据资源按钮
	$("#submitDataSourceAll").on('click',function (){
		if (sourceIdList.length>0){
			$.ajax({
       timeout:30000,
				url: window.Http + '/datasourceContent/commit/'+sourceIdList.join(','),
				type:'PUT' ,
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('提交成功')
						sourceIdList=[]
					} else {
						layer.msg(res.msg)
					}
				}
			})
		}else {
			layer.msg('当前未选中数据')
		}
	})
	// 批量删除数据资源按钮
	$('#deleteDataSourceAll').on('click',function (){
		console.log("触发点击")
		if (sourceIdList.length>0){
			console.log('删除')
			$.ajax({
       timeout:30000,
				url: window.Http + '/datasourceContent/del/'+sourceIdList.join(','),
				type:'DELETE' ,
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				success: function (res) {
					if (res.code === 200) {
						layer.msg('删除成功')
						sourceIdList=[]
						dataSourceTableRender(dataSourceParame)
					} else {
						layer.msg(res.msg)
					}
				}
			})
		}else {
			console.log('没有长度')
			layer.msg('当前未选中数据')
		}
})
	// 刷新数据通道 数据来源数量
	$('.refreshIcon').on('click',function (){
		console.log('刷新按钮')
		$.ajax({
       timeout:30000,
			url: window.Http + "/datasourceBase/operate",
			type: 'POST',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			success:function (res){
				if (res.code===200){
					layer.msg('刷新成功')
				}

			}
		})
	})
// 搜索按钮
	$('#datasource').on('click',function (){
		dataSourceParame.keyword=$('.datasource .layui-input[name="keyword"]').val()
		console.log('auditParame.title', dataSourceParame.keyword)
		dataSourceTableRender(dataSourceParame)
	})
	/******************************************功能函数部分******************************************/
	// 请求数据资源列表
	function dataSourceListReq(parame){
		return new Promise((function (resolve, reject) {
			$.ajax({
       timeout:30000,
				url: window.Http + "/customer/datasourceContent/list",
				type: 'GET',
				headers: {
					'Authorization': "Bearer " + sessionStorage.getItem('Token')
				},
				data:parame,
				success: function (res) {
					if (res.code===200){
						resolve(res)
					}else {
						layer.msg(res.msg)
						reject(new Error("请求失败")); // 失败时将错误传递给调用者
					}
				}
			})
		}))

	}
	// 表格和分页渲染
	function dataSourceTableRender(parame){
		dataSourceListReq(parame).then(res=>{
			dataSourceTable.reload({data:res.rows})
			layui.laypage.render({
				elem: 'dataSourceTablePage', //注意，这里的 test1 是 ID，不用加 # 号
				count: res.total, //数据总数，从服务端得到
				limit: 10,
				groups: 5,
				jump: function (obj, first) {
					if(!first){
						console.log('obj.curr', obj.curr)
						parame.currPage=obj.curr
						dataSourceListReq(parame).then(res=>{
							dataSourceTable.reload({data:res.rows})
						});
					}
				}
			});
		})
	}
	// 初始化渲染表格和分页
	dataSourceTableRender(dataSourceParame)
	function requestStatistic(Type){
		$.ajax({
       timeout:30000,
			url: window.Http + "/count/personal/data/table",
			type: 'GET',
			headers: {
				'Authorization': "Bearer " + sessionStorage.getItem('Token')
			},
			data: { type: Type,ownUserId:sessionStorage.getItem('UserId') },
			success: function (res) {
				if(res.code == 200){
					if(Type === 4){
						$('.datasourceTotal').html(res.data.total||0);
						$('.datasourceStatus').html(res.data.normal||0);

					}else{
						$('.databaseTotal').html(res.data.total||0);
						$('.databaseStatus').html(res.data.normal||0);
					}
				}
			}
		})
	}
	requestStatistic(4);//数据资源
})
